package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String asHex = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!asHex.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    //添加
    @Override
    public Result admin(EmployeeDTO employeeDTO) {
        //进行非空判断
        if(employeeDTO.getUsername()==null){
            return Result.error(MessageConstant.USER_NULL);
        }
        //进行判断用户账号是否存在
        Employee employee =employeeMapper.getByUsername(employeeDTO.getUsername());
        if(employee!=null){
            return Result.error(MessageConstant.ACCOUNT_FOUND);
        }
        //3.新增操作了 调用mapper接口
        employee=new Employee();
        /**
         * beanutils工具类，进行bean对象属性的拷贝使用
         * 要求，两个对象中的属性名称和属性类型必须完全一致的情况才可以拷贝成功，否则失败
         */
        BeanUtils.copyProperties(employeeDTO,employee);
        //补充没有数据内容
        //密码默认123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //创建修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //创建人修改人
        Long currentId = BaseContext.getCurrentId();
        employee.setCreateUser(currentId);
        employee.setUpdateUser(currentId);
        //状态默认1
        employee.setStatus(StatusConstant.ENABLE);
        //添加mapper接口封装到数据库中
        employeeMapper.add(employee);
        //返回数据
        return Result.success();
    }
    //分页查询
    @Override
    public Result page(EmployeePageQueryDTO employeePageQueryDTO) {
        //非空判断主要是接受的数据
        if(employeePageQueryDTO.getPage()==null){//默认页数
           employeePageQueryDTO.setPage(1);
        }
        if(employeePageQueryDTO.getPageSize()==null){
            employeePageQueryDTO.setPageSize(5);
        }
        //进行分页
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //调用mapper
        Page<Employee> employeePage= employeeMapper.findByIdPage(employeePageQueryDTO);
        //封装数据并返回
        PageResult pageResult = new PageResult();
        pageResult.setTotal(employeePage.getTotal());
        pageResult.setRecords(employeePage.getResult());
        //返回值
        return Result.success(pageResult);
    }
    //启用禁用
    @Override
    public Result updentByIdStatus(Integer status, Long id) {
        //进行非空判断
        if(status==null){
        return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        if (id==null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //调用mapper接口进行修改
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
        //返回值
        return Result.success();
    }
    //    根据id查询
    @Override
    public Result getById(Long id) {
        if(id==null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //调用接口
        Employee employee= employeeMapper.getById(id);
        employee.setPassword("***********");
        //返回值
        return Result.success(employee);
    }
    //修改员工
    @Override
    public Result update(EmployeeDTO employeeDTO) {
        //进行非空判断
        if(employeeDTO.getUsername()==null){
         return  Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //调用mapper执行修改操作
        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        //修改时间和用户
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
        //返回值
        return Result.success();
    }


}
